package com.swingson.componentprocessor.impl;

import com.swingson.SwingsonGui;
import com.swingson.componentprocessor.BaseProcessor;
import com.swingson.jsonparser.JsonObject;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;
import javax.swing.JPopupMenu;

public class PopupMenuProcessor extends BaseProcessor {

    @Override
    public JComponent createComponent(JsonObject jsonElement, JComponent parent, SwingsonGui gui) {
        JPopupMenu menu = new JPopupMenu();
        return menu;
    }

    @Override
    public Class[] getProcessingClass() {
        return new Class[]{JPopupMenu.class};
    }

    @Override
    public CustomAddToParentStrategy getCustomAddToParentStategy() {
        return new CustomAddToParentStrategy() {

            @Override
            public void addCompomentToParent(Container parent, final Component child, Object layoutParameter) {
                ((JComponent) parent).addMouseListener(new MouseAdapter() {
                    @Override
                    public void mousePressed(MouseEvent e) {
                        maybeShowPopup(e);
                    }

                    @Override
                    public void mouseReleased(MouseEvent e) {
                        maybeShowPopup(e);
                    }

                    private void maybeShowPopup(MouseEvent e) {
                        if (e.isPopupTrigger()) {
                            ((JPopupMenu) child).show(e.getComponent(),
                                    e.getX(), e.getY());
                        }
                    }
                });
            }
        };
    }

    @Override
    public void addCompomentToThis(Container parent, final Component child, Object layoutParameter) {
    }
}
